package com.ctl;

import java.security.MessageDigest;

/**
 * @Version 1.0.0
 * @Author ctl
 * @Description
 * @Date 21-8-11 下午6:40
 */
public class MD5Utils
{
    private static final String[] hexDigIts;

    static {
        hexDigIts = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
    }

    public static String MD5Encode(final String origin) {
        final String charsetname = "utf8";
        String resultString = null;
        try {
            resultString = new String(origin);
            final MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname)) {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            }
            else {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
            }
        }
        catch (Exception ex) {}
        return resultString;
    }

    public static String byteArrayToHexString(final byte[] b) {
        final StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; ++i) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    public static String byteToHexString(final byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        final int d1 = n / 16;
        final int d2 = n % 16;
        return String.valueOf(MD5Utils.hexDigIts[d1]) + MD5Utils.hexDigIts[d2];
    }

    public static void main(final String[] args) throws Exception {
        String name="ctl";
        String password="123456";
        String encode = MD5Encode(password + "treesoft" + name);
        System.out.println(name+"\t"+password+"\t"+encode);
        for (int i = 1; i <=20 ; i++) {
            name="user"+i;
            encode = MD5Encode(password + "treesoft" + name);
            System.out.println(name+"\t"+password+"\t"+encode);        }
    }
}
